//
//  XCLogManager.m
//  TestKit
//
//  Created by 帅 on 2022/11/21.
//
#define HNLOG_FLAG_PPLOG  (1 << 5) // 0...0100000

#import "XCLogManager.h"
#import <CocoaLumberjack/DDFileLogger.h>
#import <CocoaLumberjack/DDTTYLogger.h>
#import <CocoaLumberjack/CocoaLumberjack.h>

@interface XCLogManager ()
@property (nonatomic, strong) NSString *logPath;

@end

@implementation XCLogManager

+ (instancetype)sharedInstance {
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

- (instancetype)init {
    self = [super init];

    if (self) {
        [self setupFileLogger];
    }

    return self;
}

- (void)setupFileLogger {
    if ([[DDLog sharedInstance] allLoggers].count > 0) {
        return;
    }
    
    
    [DDLog addLogger:DDTTYLogger.sharedInstance withLevel:DDLogLevelDebug];
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init]; // File Logger

    NSString *logsDirectory = fileLogger.logFileManager.logsDirectory;
    self.logPath = [logsDirectory stringByAppendingPathComponent:@"log"];
    NSLog(@"%s __________  %@",__PRETTY_FUNCTION__,self.logPath);
    DDLogFileManagerDefault *fileManagerForFoodTimer = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:self.logPath];
    DDFileLogger *loggerForFoodTimer = [[DDFileLogger alloc] initWithLogFileManager:fileManagerForFoodTimer];
    loggerForFoodTimer.rollingFrequency = kDDDefaultLogRollingFrequency; // 24 hour rolling
    loggerForFoodTimer.maximumFileSize = (6*kDDDefaultLogMaxFileSize); //  用文件大小 rolling
    loggerForFoodTimer.logFileManager.maximumNumberOfLogFiles = kDDDefaultLogMaxNumLogFiles;
    loggerForFoodTimer.logFileManager.logFilesDiskQuota = 2*kDDDefaultLogFilesDiskQuota;

    [DDLog addLogger:loggerForFoodTimer withLevel:HNLOG_FLAG_PPLOG];
}

+ (NSString *)logpath {
    return [XCLogManager sharedInstance].logPath;
}

+ (void)log:(NSString *)frmt, ...{

    va_list args;

    if (frmt) {
        va_start(args, frmt);

        NSString *message = [[NSString alloc] initWithFormat:frmt arguments:args];

        va_end(args);

        va_start(args, frmt);
        
        [[XCLogManager sharedInstance] log:message];

        va_end(args);
    }
}

-(void)log:(NSString *)frmt{
    
//#ifdef DEBUG
//    NSLog(@"%@", frmt);
//#else
    [DDLog log:YES level:DDLogLevelAll flag:(HNLOG_FLAG_PPLOG | DDLogFlagDebug) context:1 file:__FILE__ function:__PRETTY_FUNCTION__ line:__LINE__ tag:Nil format:@"%@", (frmt)];
//#endif
}

+ (void)print:(NSString *)frmt{
    [[XCLogManager sharedInstance] log:frmt];
}

@end
